package com.example.productservice.service;

import com.example.productservice.exception.ResourceNotFoundException;
import com.example.productservice.model.Category;
import com.example.productservice.model.Product;
import com.example.productservice.repository.CategoryRepository;
import com.example.productservice.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商品服务实现类
 * 提供商品相关的业务逻辑处理，包括商品的CRUD操作、分类管理、库存控制等
 * 
 * @author SimpleShop
 * @version 1.0
 */
@Service
public class ProductService {

    /**
     * 商品数据访问对象
     */
    private final ProductRepository productRepository;
    
    /**
     * 分类数据访问对象
     */
    private final CategoryRepository categoryRepository;

    /**
     * 构造函数，注入依赖
     * 
     * @param productRepository 商品数据访问对象
     * @param categoryRepository 分类数据访问对象
     */
    @Autowired
    public ProductService(ProductRepository productRepository,
                          CategoryRepository categoryRepository) {
        this.productRepository = productRepository;
        this.categoryRepository = categoryRepository;
    }

    /**
     * 获取所有商品
     */
    public List<Product> getAllProducts() {
        return productRepository.findAll();
    }

    /**
     * 根据ID获取商品
     */
    public Product getProductById(Long id) {
        return productRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("商品未找到，ID: " + id));
    }

    /**
     * 创建新商品
     */
    @Transactional
    public Product createProduct(Product product) {
        // 如果商品有分类，确保分类存在
        if (product.getCategory() != null && product.getCategory().getId() == null) {
            // 如果分类没有ID但有名称，尝试按名称查找
            if (product.getCategory().getName() != null) {
                Category existingCategory = categoryRepository.findByName(product.getCategory().getName());
                if (existingCategory != null) {
                    product.setCategory(existingCategory);
                } else {
                    // 创建新分类
                    Category newCategory = new Category();
                    newCategory.setName(product.getCategory().getName());
                    product.setCategory(categoryRepository.save(newCategory));
                }
            }
        }
        return productRepository.save(product);
    }

    /**
     * 更新商品信息
     */
    @Transactional
    public Product updateProduct(Long id, Product productDetails) {
        Product product = getProductById(id);

        // 更新商品信息
        if (productDetails.getName() != null) {
            product.setName(productDetails.getName());
        }
        if (productDetails.getDescription() != null) {
            product.setDescription(productDetails.getDescription());
        }
        if (productDetails.getPrice() != null) {
            product.setPrice(productDetails.getPrice());
        }
        if (productDetails.getStock() != null) {
            product.setStock(productDetails.getStock());
        }
        if (productDetails.getCategory() != null) {
            product.setCategory(productDetails.getCategory());
        }

        return productRepository.save(product);
    }

    /**
     * 删除商品
     */
    @Transactional
    public void deleteProduct(Long id) {
        Product product = getProductById(id);
        productRepository.delete(product);
    }

    /**
     * 搜索商品（按名称模糊匹配）
     */
    public List<Product> searchProducts(String keyword) {
        return productRepository.findByNameContainingIgnoreCase(keyword);
    }

    /**
     * 根据分类ID获取商品
     */
    public List<Product> getProductsByCategory(Long categoryId) {
        return productRepository.findByCategoryId(categoryId);
    }

    /**
     * 获取所有分类
     */
    public List<Category> getAllCategories() {
        return categoryRepository.findAll();
    }

    /**
     * 根据ID获取分类
     */
    public Category getCategoryById(Long id) {
        return categoryRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("分类未找到，ID: " + id));
    }

    /**
     * 创建新分类
     */
    public Category createCategory(Category category) {
        return categoryRepository.save(category);
    }

    /**
     * 更新分类信息
     */
    @Transactional
    public Category updateCategory(Long id, Category categoryDetails) {
        Category category = getCategoryById(id);
        
        if (categoryDetails.getName() != null) {
            category.setName(categoryDetails.getName());
        }
        
        return categoryRepository.save(category);
    }

    /**
     * 删除分类
     */
    @Transactional
    public void deleteCategory(Long id) {
        Category category = getCategoryById(id);
        
        // 检查是否有商品使用此分类
        List<Product> productsInCategory = productRepository.findByCategoryId(id);
        if (!productsInCategory.isEmpty()) {
            throw new RuntimeException("无法删除分类，该分类下还有商品");
        }
        
        categoryRepository.delete(category);
    }

    /**
     * 扣减库存（用于订单服务调用）
     * @param productId 商品ID
     * @param quantity 扣减数量
     * @return 是否扣减成功
     */
    @Transactional
    public boolean reduceStock(Long productId, int quantity) {
        Product product = getProductById(productId);

        if (product.getStock() < quantity) {
            throw new RuntimeException("库存不足，商品ID: " + productId);
        }

        product.setStock(product.getStock() - quantity);
        productRepository.save(product);
        return true;
    }
}